// api.js
import {
	cacheVideo, doClearCache
} from '../utils/utils';
import {
	TOKENNAME,
} from '@/config/app';
let version = [];
let header = {}
header[TOKENNAME] = uni.getStorageSync('LOGIN_STATUS_TOKEN') || '';
import {
	HTTP_REQUEST_URL
} from '@/config/app.js'

export function fetchVersion(page = 1) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: HTTP_REQUEST_URL + '/api/xilumarket/user/videoList',
			method: 'POST',
			header,
			data: {
				page: page,
				size: 2000,
			},
			success: async (res) => {
				uni.setStorageSync('videoData', [])
				version = res.data.data.data;
				if (version.length > 0) {
					let j = version.length
					for (let i = 0; i < j; i++) {
						let item = version[i]
						item.coverStatus = true
						item.flag = true
						item.loading = true
					}
					uni.setStorageSync('videoData', version)
				}
			},
			fail: (err) => {
				console.log(err);
				reject()
			}
		});
	})
}

export function refreshVideo(){
	uni.$store.state.refreshVideo=true
	uni.setStorageSync('videoData',[])
	uni.$store.commit('setVideoList',[])
	doClearCache()
	fetchVersion()
	cache()
}
//设置store 并开始缓存
export async function cache() {
	let videoList = uni.getStorageSync('videoData')
	if (videoList && videoList.length > 0) {
		uni.$store.commit('setVideoList',videoList)
		uni.hideLoading()
		for (let i = 0; i < 10; i++) {
			const localUrl = await cacheVideo({
				url: uni.$store.state.videoList[i].image
			})
			uni.$store.state.videoList[i].image = localUrl
			uni.$store.state.videoList[i].loading = false
		}
	}else{
		let a = setTimeout(()=>{
			cache()
			clearTimeout(a)
		},500)
	}
}
// 导出version的引用，但是注意：由于异步，刚开始是空数组
export default {
	version,
	fetchVersion,
	cache,
	refreshVideo
};